export const parseData = (source) => {
  try {
    return JSON.parse(source)
  } catch (error) {
    console.log("JSON parse 出错", error)
    return {}
  }
}

export async function requestSSE(url, data, callbacks) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify(data)
    });

    if (!response.ok || !response.body) {
      throw new Error(`SSE connection failed: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log("ock")
        if (callbacks.onComplete) callbacks.onComplete();
        break;
      }

      buffer += decoder.decode(value, { stream: true });

      // 处理可能的多条消息
      while (buffer.includes('\n\n')) {
        const splitIndex = buffer.indexOf('\n\n');
        const message = buffer.slice(0, splitIndex);
        buffer = buffer.slice(splitIndex + 2);

        // 解析SSE消息格式
        let event = 'message';
        let data = '';

        message.split('\n').forEach(line => {
          if (line.startsWith('event:')) {
            event = line.replace('event:', '').trim();
          } else if (line.startsWith('data:')) {
            data = line.replace('data:', '').trim();
          }
        });

        // 触发回调
        if (callbacks[event]) {
          try {
            callbacks[event](JSON.parse(data));
          // eslint-disable-next-line no-unused-vars
          } catch (e) {
            callbacks[event](data);
          }
        } else if (callbacks.onMessage) {
          try {
            callbacks.onMessage(event, JSON.parse(data));
          // eslint-disable-next-line no-unused-vars
          } catch (e) {
            callbacks.onMessage(event, data);
          }
        }
      }
    }
  } catch (error) {
    if (callbacks.onError) callbacks.onError(error);
  }
}